//
//  UploadPhotoClass.m
//  QinRen
//
//  Created by easaa on 15/5/23.
//  Copyright (c) 2015年 Donny. All rights reserved.
//

#import "UploadPhotoClass.h"
#import "Unit.h"


@interface UploadPhotoClass ()<UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
{
    NSDictionary *audioDictionary;

}

@property (nonatomic,strong) UIViewController *viewController;
@property (nonatomic,copy) void(^uploadCompleteBlock)(id obj,NSError *error);
@property (nonatomic,assign) BOOL isUpdate;
@property (nonatomic,copy) void(^completeBlock)(void);



@end

@implementation UploadPhotoClass



- (void)uploadPhotoWithPickImageInView:(UIViewController *)viewController withBlock:(void (^)(id, NSError *))block;
{
    if (block) {
        self.uploadCompleteBlock = block;
    }
    self.viewController = viewController;
    [self showAlertViewo:viewController];
}


- (void)uploadPhotoWithPickImageInView:(UIViewController *)viewController isUpdateUserInfo:(BOOL)isUpdate withBlock:(void (^)(id response, NSError *error))block updateUserInfoBlock:(void(^)(void))completeBlock;
{
    self.isUpdate = isUpdate;
    if (completeBlock) {
        self.completeBlock = completeBlock;
    }
    [self uploadPhotoWithPickImageInView:viewController withBlock:block];
}


- (void)showAlertViewo:(UIViewController *)viewController
{
    
    UIView *view = viewController.view;
        UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"选择图片"
                                                            delegate:self
                                                   cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:nil
                                                   otherButtonTitles:@"拍照",@"从相册中选取", nil];
        [action showInView:view];
    
}


#pragma mark - UIActionSheet delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger sourceType;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        switch (buttonIndex)
        {
            case 0:
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1:
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                return;
                break;
        }
    }
    else
    {
        switch (buttonIndex)
        {
            case 0:
                return;
                break;
            case 1:
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                return;
                break;
        }
        
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self.viewController presentViewController:imagePickerController animated:YES completion:^{
        NSLog(@"gg");
    }];
    //
    
}







#pragma mark - UIImagePicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//    

    
    UIImage *fileImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *dateString = [self creatTimeData];
    //生成文件名：
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString  *diskCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"qinren/image"];
    
    //没有文件夹 创建个文件夹
    if (![[NSFileManager defaultManager] fileExistsAtPath:diskCachePath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    
    float scale = 0.0;
    if (fileImage.size.width > 320)
    {
        scale = 320 / fileImage.size.width;
    }
    else
    {
        scale = 1.0;
    }
    //压缩图片
    UIImage *sendImage = [self scaleImage:[Unit rotateImage:fileImage] toScale:scale];
    
    //把图片转成data 存进沙盒中
    NSString *pathString = [diskCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",dateString]];
    NSData *imageData = UIImagePNGRepresentation(sendImage);
    [imageData writeToFile:pathString atomically:YES];
    
 
  
    //退出相册
    [self.viewController dismissViewControllerAnimated:YES completion:^{
        [NSThread detachNewThreadSelector:@selector(uploadImage:) toTarget:self withObject:sendImage];
    }];

    
}
#pragma mark 头像加密 上传
- (void)uploadImage:(UIImage *)image
{
    NSData *data = UIImageJPEGRepresentation(image , 0.1);
    data = UIImagePNGRepresentation(image);
    NSString *tem = [data base64Encoding];
    tem =[tem stringByReplacingOccurrencesOfString:@"+" withString:@"|JH|"];
    tem=[tem stringByReplacingOccurrencesOfString:@" " withString:@"|KG|"];
    NSString *lTmp = [NSString stringWithFormat:@"%c",'\n'];
    NSString *lTmp2 = [NSString stringWithFormat:@"%c",'\r'];
    tem= [tem stringByReplacingOccurrencesOfString:lTmp withString:@"|HC|"];
    tem= [tem stringByReplacingOccurrencesOfString:lTmp2 withString:@"|HC|"];
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //    NSInteger sec = [date timeIntervalSinceReferenceDate];
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSString stringWithFormat:@"123456.png"],@"name",/*图片名称:abc.jpg*/
                                nil];
    // DLog(@"%@",parameters);
    NSString *urlStr = [manager requestStringWithParameters:parameters method:@"set.picture.add"];
    NSLog(@"urlStr= %@",urlStr);
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlStr parameters:/*base64*/[NSDictionary dictionaryWithObject:tem forKey:@"img"] success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
     
         
//         [ZZTool hideHud:self.view animated:YES];
         NSString *resposeString ;
         if ([responseObject isKindOfClass:[NSData class]]){
             resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
         } else {
             resposeString = responseObject;
         }
         NSString *jsonString = [DataParser parseString:resposeString];
         id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
         // NSLog(@"dictonary :%@ error = %@",[dictionary description],[dictionary objectForKey:@"error"]);
         
         
         if (self.uploadCompleteBlock) {
             self.uploadCompleteBlock(dictionary,nil);
         }
         //
//         _imgUrl = dictionary[@"error"];
         if ([[dictionary objectForKey:@"total"]intValue] == 1)
         {
            // [ZZTool showAlert:@"上传图片成功"];
            
             if (self.isUpdate) {
                 if (self.completeBlock) {
                     
                   //  [self updateUserInfo:dictionary withBlock:self.completeBlock];

                 }

             }
             
             
         }else
         {
             //[ZZTool showAlert:@"上传图片失败"];
             DLog(@"上传失败");
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"error = %@",error);
         
         if (self.uploadCompleteBlock) {
             self.uploadCompleteBlock(nil,error);
         }
         
     }];
    
}

//-(void)updateUserInfo:(NSDictionary *)dic withBlock:(void(^)(void))block
//{
//    
//    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//   __block User *user = [User sharedUser];
//    
//   // NSDictionary *parameters = @{@"suid":user.uid,@"icon":dic[@"error"]};
//   // [manager GetWithParameters:parameters method:@"set.user.info" success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        if (block) {
//           // user.icon = dic[@"error"];
//            block();
//        }
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
//        
//    }];
//    
//}


//时间
-(NSString*)creatTimeData
{
    NSDateFormatter *dateFormateter = [[NSDateFormatter alloc] init];
    [dateFormateter setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
    NSString *dataString = [dateFormateter stringFromDate:[NSDate date]];
    return dataString;
}

#pragma mark 等比压缩图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}



@end
